package com.bqjr.cloud.zuul.ribbon;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.bqjr.cloud.zuul.model.ServerInfo;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import com.netflix.zuul.context.RequestContext;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RibbonRule extends RoundRobinRule {
	
	@Autowired
	private RouteManager routeManager;

	public Server choose(Object key) {
		Server server = null;
		ServerInfo serverInfo = routeManager.choose(RequestContext.getCurrentContext());
		if (serverInfo != null) {
			List<Server> list = getLoadBalancer().getAllServers();
			for (Server svr : list) {
				if (svr.getHost().equals(serverInfo.getHost()) && svr.getPort() == serverInfo.getPort().intValue()) {
					server = svr;
					break;
				}
			}
		}
		if (server == null) {
			server = super.choose(key);
		}
		return server;
	}

}
